package com.quick.calcu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quick.calcu.entity.ClassInfo;
import com.quick.calcu.entity.Student;
import com.quick.calcu.entity.Teacher;
import com.quick.calcu.entity.WrongQuestion;
import com.quick.calcu.mapper.ClassMapper;
import com.quick.calcu.mapper.StudentMapper;
import com.quick.calcu.service.ClassInfoService;
import com.quick.calcu.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ClassInfoServiceImpl extends ServiceImpl<ClassMapper, ClassInfo> implements ClassInfoService {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<ClassInfo> getClassesByGrade(Integer grade) {
        LambdaQueryWrapper<ClassInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClassInfo::getGrade, grade);
        return list(wrapper);
    }

    @Override
    public List<ClassInfo> getClassesByTeacherId(Long teacherId) {
        LambdaQueryWrapper<ClassInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClassInfo::getTeacherId, teacherId);
        return list(wrapper);
    }


    @Override
    @Transactional
    public boolean addStudentToClass(Long classId, Long studentId) {
        // 查询班级
        ClassInfo clazz = getById(classId);
        if (clazz == null) {
            return false;
        }

        // 更新学生数量
        clazz.setStudentCount(clazz.getStudentCount() + 1);
        updateById(clazz);

        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            throw new IllegalArgumentException("学生不存在");
        }

        student.setClassId(classId);
        return studentMapper.updateById(student) > 0;
    }

    @Override
    public List<ClassInfo> getClassWithTeacher(Long teacherId) {
        // 查询班级
        LambdaQueryWrapper<ClassInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClassInfo::getTeacherId, teacherId);

        return list(wrapper);
    }
}